package com.yicoollxing.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yicoollxing.common.ResponseCode;
import com.yicoollxing.common.ServerResponse;
import com.yicoollxing.dao.mapper.VoucherMapper;
import com.yicoollxing.pojo.Voucher;
import com.yicoollxing.service.IVoucherService;


@Service("iVoucherService")
public class VoucherServiceImpl implements IVoucherService {
    
	
	@Autowired
	private VoucherMapper voucherMapper;
	
	public ServerResponse modifyAndAdd(Voucher voucher){
		if (voucher == null) {
			return ServerResponse.createByErrorCodeMessage(
					ResponseCode.ILLEGAL_ARGUMENT.getCode(),
					ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		//id为null新增，否则修改
		if(voucher.getId()==null){
			int rawResult=voucherMapper.insertSelective(voucher);
			if(rawResult==0){
				return ServerResponse.createByErrorMessage("添加优惠券失败"); 
			}else{
				return ServerResponse.createBySuccessMessage("添加优惠券成功"); 
			}
		}else{
			voucher.setUpdateTime(new Date());
			int rawResult=voucherMapper.updateByPrimaryKeySelective(voucher);
			if(rawResult==0){
				return ServerResponse.createByErrorMessage("修改优惠券失败"); 
			}else{
				return ServerResponse.createBySuccessMessage("修改优惠券成功"); 
			}
		}
	}
	
	public ServerResponse  delVoucher(Integer voucherId){
		if(voucherId==null){
			return ServerResponse.createByErrorCodeMessage(
					ResponseCode.ILLEGAL_ARGUMENT.getCode(),
					ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		int rawResult=voucherMapper.deleteByPrimaryKey(voucherId);
		if(rawResult==0){
			return ServerResponse.createByErrorMessage("删除优惠券失败"); 
		}
		return ServerResponse.createBySuccessMessage("删除优惠券成功"); 
	}
	
	public ServerResponse search(Integer voucherId,Integer useClassId,String sourceName,Integer pageNum,Integer pageSize){
		
		if(StringUtils.isNotBlank(sourceName)){
			sourceName=new StringBuilder().append("%").append(sourceName).append("%").toString();
		}
		List<Voucher> voucherList=voucherMapper.searchVoucher(voucherId, useClassId, sourceName);
		PageHelper pageHelper=new PageHelper();
		pageHelper.startPage(pageNum, pageSize);
		PageInfo pageInfo=new PageInfo(voucherList);
		return ServerResponse.createBySuccess(voucherList);
	}
}
